import pymysql

from config import Config

conf = Config()

### 使用pymysql操作原生sql

db_info = {
    'host': conf.MYSQL_HOST,
    'user': conf.MYSQL_USER,
    'password': conf.MYSQL_PASS,
    'port': int(conf.MYSQL_PORT),
    'charset': 'utf8',
    'cursorclass': pymysql.cursors.Cursor,
    'database': conf.MYSQL_DB,
    # 'client_flag': CLIENT.MULTI_STATEMENTS,
}


# 连接数据库
def connect_db():
    try:
        connection = pymysql.connect(**db_info)
    except Exception as e:
        print(e)
        raise
    return connection


def db_exec_one(one_sql: str) -> bool:
    db_success = False
    # 获取参数
    con = connect_db()
    print(one_sql)
    try:
        with con.cursor() as cursor:
            cursor.execute(one_sql)
            # 提交
            con.commit()
            db_success = True
    except Exception as e:
        print("数据库提交错误：")
        print(e)
        con.rollback()
    finally:
        con.close()
    # 成功commit才会返回True，负责默认Fasl
    return db_success


def db_exec_many(table, fields, values_list, sql="") -> bool:
    db_success = False
    # 获取参数
    con = connect_db()
    f_count = fields.strip(",").count(",") + 1
    values = ("%s," * f_count).rstrip(",")
    if not sql:
        sql = "INSERT INTO {}({}) VALUES({});".format(table, fields, values)
    print(sql)
    try:
        with con.cursor() as cursor:
            cursor.executemany(sql, values_list)
            # 提交
            con.commit()
            db_success = True
    except Exception as e:
        print("数据库提交错误：")
        print(e)
        con.rollback()
    finally:
        con.close()
    # 成功commit才会返回True，负责默认Fasl
    return db_success
